package q39_combinationSum;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 使用相对标准的模版化写法
 */
public class Solution_2 {
    private List<List<Integer>> res;
    private List<Integer> path;
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        res = new ArrayList<>();
        path = new ArrayList<>();
        Arrays.sort(candidates);
        dfs(candidates,target,0,0);
        return res;
    }

    private void dfs(int[] candidates,int target,int sum,int begin){
        if(sum > target){
            return;
        }

        if (sum == target){
            res.add(new ArrayList<>(path));
        }

        // 其实这里可以优化，如果发现sum + candidate[i]已经超过target就直接结束
        // 能够从击败14%提高到92%的时间速率
        for (int i = begin; i < candidates.length && sum + candidates[i] <= target; i++) {
            path.add(candidates[i]);
            sum += candidates[i];
            dfs(candidates, target, sum, i);
            sum -= candidates[i];
            path.remove(path.size() - 1);
        }
    }
}
